package com.inossem.warehousestorage_inossem.adapter.outStorage;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.inossem.utils.base.ArithUtils;
import com.inossem.utils.base.RegexUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.out_storage.OutStoragePickingDetailActivity;
import com.inossem.warehousestorage_inossem.bean.outStorage.OutStoragePickingAddBatchBean;
import com.inossem.warehousestorage_inossem.bean.outStorage.OutStoragePickingBatchListBean;
import com.inossem.warehousestorage_inossem.bean.outStorage.OutStoragePickingOverviewBean;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.request.outStorage.OutStoragePickingAddBatchRequest;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by leij on 2017/6/6.
 */

public class PickingOutStorageDetailListAdapter extends BaseAdapter {

    public static final String CONFIRM = "1";

    private static final String FOCUS_BATCH = "1";

    private Context mContext;
    private LayoutInflater inflater;
    private OutStoragePickingDetailActivity.OutStoragePickingDetailListener mOutStoragePickingDetailListener;
    private List<OutStoragePickingBatchListBean.DataBean.BatchListBean> mBatchList;
    private String mSerial, mIsFocusBatch, mBatchNumber, mMaterielCode, mMaterielDescription, mUnit, mCanSendNumber, mActualSendNumber, mInventoryAddress, mInventoryAddressCode, mFactoryCode, mPickingClassify, mUseDepartment;
    private EditText batchNumberEditText;
    private TextView actualSendNumber;

    public List<OutStoragePickingBatchListBean.DataBean.BatchListBean> getmBatchList() {
        return mBatchList;
    }

    public String getmActualSendNumber() {
        return mActualSendNumber;
    }

    public PickingOutStorageDetailListAdapter(Context context, OutStoragePickingOverviewBean.DataBean.MaterielListBean materielDetail, List<OutStoragePickingBatchListBean.DataBean.BatchListBean> batchList, String batchNumber, String pickingClassify, String useDepartment, OutStoragePickingDetailActivity.OutStoragePickingDetailListener outStoragePickingDetailListener) {
        mContext = context;
        mBatchList = batchList == null ? new ArrayList<>() : batchList;
        mIsFocusBatch = materielDetail.getIsFocusBatch();
        mBatchNumber = batchNumber;
        mPickingClassify = pickingClassify;
        mUseDepartment = useDepartment;
        mSerial = materielDetail.getSerial();
        mMaterielCode = materielDetail.getMaterielCode();
        mMaterielDescription = materielDetail.getMaterielDescription();
        mUnit = materielDetail.getUnit();
        mCanSendNumber = materielDetail.getCanSendNumber();
        mInventoryAddressCode = materielDetail.getInventoryAddressCode();
        mInventoryAddress = mInventoryAddressCode + " - " + materielDetail.getInventoryAddressValue();
        mFactoryCode = materielDetail.getFactoryCode();
        mOutStoragePickingDetailListener = outStoragePickingDetailListener;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return mBatchList.size() + 1;
    }

    @Override
    public Object getItem(int position) {
        return mBatchList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (position == 0) {
            convertView = inflater.inflate(R.layout.view_out_storage_picking_detail_first_item, null);
            TextView serialNumber = (TextView) convertView.findViewById(R.id.serialNumber);
            TextView materielCode = (TextView) convertView.findViewById(R.id.materielCode);
            TextView materielDescription = (TextView) convertView.findViewById(R.id.materielDescription);
            TextView canSendNumber = (TextView) convertView.findViewById(R.id.canSendNumber);
            actualSendNumber = (TextView) convertView.findViewById(R.id.actualSendNumber);
            TextView inventoryAddress = (TextView) convertView.findViewById(R.id.inventoryAddress);
            batchNumberEditText = (EditText) convertView.findViewById(R.id.batchNumber);
            ImageView search = (ImageView) convertView.findViewById(R.id.search);
            Button defaultBatch = (Button) convertView.findViewById(R.id.defaultBatch);
            Button addBatch = (Button) convertView.findViewById(R.id.addBatch);
            serialNumber.setText(mSerial);
            materielCode.setText(mMaterielCode);
            materielDescription.setText(mMaterielDescription);
            canSendNumber.setText(mCanSendNumber + mUnit);
            mActualSendNumber = calculatedTotal();
            actualSendNumber.setText("".equals(mActualSendNumber) ? "" : (mActualSendNumber + mUnit));
            inventoryAddress.setText(mInventoryAddress);
            batchNumberEditText.setText(mBatchNumber);
//            batchNumber.addTextChangedListener(new QRCodeEditTextWatcher(batchNumber) {
//                @Override
//                public void onScan(String text) {
//                    Utils.closeSoftKeyboard(mContext, batchNumber);
//                    addBatchRequest(mContext, true, text, null);
//                }
//            });
            addBatch.setOnClickListener(new NoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    if (FOCUS_BATCH.equals(mIsFocusBatch)) {
                        Utils.middleToast(mContext, "强制批次无法添加批次信息");
                    } else {
                        mOutStoragePickingDetailListener.selectItem(0);
                        batchNumberEditText.requestFocus();
                    }
                }
            });
            defaultBatch.setOnClickListener(new NoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    DialogUtils.getPickingOutStorageNumberDialog(mContext, "请输入建议批次数量", Double.parseDouble(mCanSendNumber), new DialogUtils.EditTextDialogListener() {
                        @Override
                        public void onConfirm(Dialog dialog, String result) {
                            if (TextUtils.isEmpty(result)) {
                                Utils.middleToast(mContext, "建议批次数量不可以为空");
                            } else if (!RegexUtils.checkDecimal(result)) {
                                Utils.middleToast(mContext, "建议批次数量不符合规范");
                            } else {
                                mOutStoragePickingDetailListener.getDefaultBatch(result);
                                dialog.cancel();
                            }
                        }
                    }).show();
                }
            });
            search.setOnClickListener(new NoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    Utils.closeSoftKeyboard(mContext, search);
                    addBatchRequest(mContext, false, null, batchNumberEditText.getText().toString());
                }
            });
        } else {
            OutStoragePickingBatchListBean.DataBean.BatchListBean pickingOutStorageItem = mBatchList.get(position - 1);
            convertView = inflater.inflate(R.layout.view_out_storage_picking_detail, null);
            TextView positionTextView = (TextView) convertView.findViewById(R.id.position);
            TextView inStorageDate = (TextView) convertView.findViewById(R.id.inStorageDate);
            TextView batch = (TextView) convertView.findViewById(R.id.batch);
            EditText outStorageNumber = (EditText) convertView.findViewById(R.id.outStorageNumber);
            TextView unit = (TextView) convertView.findViewById(R.id.unit);
            TextView status = (TextView) convertView.findViewById(R.id.status);
            positionTextView.setText(pickingOutStorageItem.getPosition());
            inStorageDate.setText(pickingOutStorageItem.getInStorageDate());
            batch.setText(pickingOutStorageItem.getBatch());
            outStorageNumber.setText(pickingOutStorageItem.getOutStorageNumber());
            unit.setText(pickingOutStorageItem.getUnit());
            if (pickingOutStorageItem.getIsConfirm() != null) {
                status.setText("状态：OK");
                status.setOnClickListener(null);
            } else {
                status.setText("点击扫码确认");
                status.setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View v) {
//                    Utils.middleToast(mContext, outStorageNumber.getText().toString());
                        mOutStoragePickingDetailListener.selectItem(0);
                        batchNumberEditText.requestFocus();
                    }
                });
            }
            outStorageNumber.setOnFocusChangeListener((View v, boolean hasFocus) -> {
                if (!hasFocus) {
                    String outStorageNumberStr = outStorageNumber.getText().toString();
//                    检测当前仓位出库数量是否为空
                    if (!TextUtils.isEmpty(outStorageNumberStr)) {
                        //正则表达式校验输入框内容
                        if (RegexUtils.checkDecimal(outStorageNumberStr)) {
                            //检测输入数量是否超过当前仓位库存
                            if (checkInventory(pickingOutStorageItem.getInventoryNumber(), outStorageNumberStr)) {
                                pickingOutStorageItem.setOutStorageNumber(outStorageNumberStr);
                                mActualSendNumber = calculatedTotal();
                                actualSendNumber.setText("".equals(mActualSendNumber) ? "" : (mActualSendNumber + mUnit));
                            } else {
                                Utils.middleToast(mContext, "超过当前仓位库存");
                                outStorageNumber.setText("");
                                pickingOutStorageItem.setOutStorageNumber("");
                                mActualSendNumber = calculatedTotal();
                                actualSendNumber.setText("".equals(mActualSendNumber) ? "" : (mActualSendNumber + mUnit));
                            }
                        } else {
//                            Utils.middleToast(mContext, "输入内容不合法");
//                            outStorageNumber.setText("");
                            pickingOutStorageItem.setOutStorageNumber("");
                            mActualSendNumber = calculatedTotal();
                            actualSendNumber.setText("".equals(mActualSendNumber) ? "" : (mActualSendNumber + mUnit));
                        }
                    } else {
                        pickingOutStorageItem.setOutStorageNumber("");
                        mActualSendNumber = calculatedTotal();
                        actualSendNumber.setText("".equals(mActualSendNumber) ? "" : (mActualSendNumber + mUnit));
                    }
                }
            });
            outStorageNumber.setText(pickingOutStorageItem.getOutStorageNumber());
            if (FOCUS_BATCH.equals(mIsFocusBatch)) {
                outStorageNumber.setFocusable(false);
                outStorageNumber.setBackground(null);
            }
            convertView.setOnLongClickListener((View v) -> {
                DialogUtils.getConfirmDialog(mContext, "确定要删除仓位：" + pickingOutStorageItem.getPosition() + ",批次：" + pickingOutStorageItem.getBatch() + "的行项目吗?", new DialogUtils.ConfirmDialogListener() {
                    @Override
                    public void onConfirm(Dialog dialog) {
                        dialog.cancel();
                        removeItem(pickingOutStorageItem);
                        notifyDataSetChanged();
                    }
                }).show();
                return true;
            });
        }
        return convertView;
    }

    public void addBatchRequest(Context context, boolean isScanner, String scannerContent, String batchNumber) {
        if (TextUtils.isEmpty(scannerContent) && TextUtils.isEmpty(batchNumber)) {
            Utils.middleToast(mContext, "内容不可以为空");
            return;
        }
        mBatchNumber = batchNumber;
        batchNumberEditText.setText(batchNumber);
        int index = checkPosition(mBatchList, batchNumber);
        if (index != -1) {
            notifyDataSetChanged();
            mOutStoragePickingDetailListener.selectItem(index);
        } else {
            if (FOCUS_BATCH.equals(mIsFocusBatch)) {
                Utils.middleToast(mContext, "仓位信息未找到，强制批次无法添加批次信息");
            } else {
                OutStoragePickingAddBatchRequest.request(mContext, isScanner, scannerContent, batchNumber, mMaterielCode, mFactoryCode, mInventoryAddressCode, mPickingClassify, mUseDepartment, new GsonBeanListener<OutStoragePickingAddBatchBean>() {
                    @Override
                    public void onSuccess(OutStoragePickingAddBatchBean bean) {
                        List<OutStoragePickingBatchListBean.DataBean.BatchListBean> realBatchList = filter(mBatchList, bean.getData().getBatchList());
                        int size = realBatchList.size();
                        if (size > 1) {
                            DialogUtils.getAddBatchDialog(mContext, realBatchList, new DialogUtils.AddBatchListener() {
                                @Override
                                public void onSelect(Dialog dialog, OutStoragePickingBatchListBean.DataBean.BatchListBean bean) {
                                    mBatchList.add(bean);
                                    notifyDataSetChanged();
                                }
                            }).show();
                        } else if (size == 1) {
                            mBatchList.addAll(realBatchList);
                            notifyDataSetChanged();
                        } else if (size == 0) {
                            Utils.middleToast(mContext, "已经添加该仓位");
                        }
                    }
                });
            }
        }
    }

    //计算实发数量
    private String calculatedTotal() {
        double result = 0D;
        for (int i = 0; i < mBatchList.size(); i++) {
            OutStoragePickingBatchListBean.DataBean.BatchListBean batchItem = mBatchList.get(i);
            double actualSendNumberDou;
            if (TextUtils.isEmpty(batchItem.getOutStorageNumber())) {
                actualSendNumberDou = 0D;
            } else {
                actualSendNumberDou = Double.parseDouble(batchItem.getOutStorageNumber());
            }
            result = ArithUtils.add(result, actualSendNumberDou);
        }
        return result == 0D ? "" : String.valueOf(result);
    }

    private void removeItem(OutStoragePickingBatchListBean.DataBean.BatchListBean pickingOutStorageItem) {
        for (int i = 0; i < mBatchList.size(); i++) {
            OutStoragePickingBatchListBean.DataBean.BatchListBean batchItem = mBatchList.get(i);
            if (batchItem.getPosition().equals(pickingOutStorageItem.getPosition()) && batchItem.getBatch().equals(pickingOutStorageItem.getBatch())) {
                mBatchList.remove(batchItem);
                break;
            }
        }
    }

    private List<OutStoragePickingBatchListBean.DataBean.BatchListBean> filter(List<OutStoragePickingBatchListBean.DataBean.BatchListBean> allData, List<OutStoragePickingBatchListBean.DataBean.BatchListBean> returnData) {
        List<OutStoragePickingBatchListBean.DataBean.BatchListBean> repeatList = new ArrayList<>();
        for (int i = 0; i < returnData.size(); i++) {
            OutStoragePickingBatchListBean.DataBean.BatchListBean returnItem = returnData.get(i);
            for (int j = 0; j < allData.size(); j++) {
                OutStoragePickingBatchListBean.DataBean.BatchListBean allItem = allData.get(j);
                if (allItem.getPosition().equals(returnItem.getPosition()) && allItem.getBatch().equals(returnItem.getBatch())) {
                    repeatList.add(returnItem);
                }
            }
        }
        returnData.removeAll(repeatList);
        return returnData;
    }

    private boolean checkInventory(String inventoryNumber, String number) {
        double inventoryNumberDou = Double.parseDouble(inventoryNumber);
        double numberDou = Double.parseDouble(number);
        if (inventoryNumberDou >= numberDou) {
            return true;
        } else {
            return false;
        }
    }

    private int checkPosition(List<OutStoragePickingBatchListBean.DataBean.BatchListBean> batchList, String position) {
        int result = -1;
        for (int i = 0; i < batchList.size(); i++) {
            OutStoragePickingBatchListBean.DataBean.BatchListBean batchItem = batchList.get(i);
            if (batchItem.getPosition().equals(position)) {
                batchItem.setIsConfirm(CONFIRM);
                result = i + 1;
            }
        }
        return result;
    }
}
